package WebAll.dao.impl;

import WebAll.utils.JdbcUtils;
import com.sun.xml.internal.ws.api.message.Header;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import javax.management.Query;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author ：Yan Guang
 * @date ：Created in 2020/6/3 9:00
 * @description：
 */
public abstract class BaseDAO {
    private QueryRunner queryRunner = new QueryRunner();//这里就是新建查询

    public int update(String sql,Object ...args){
        Connection connection= JdbcUtils.getconnection();
        try {
            return queryRunner.update(connection,sql,args);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JdbcUtils.close(connection);
        }
        return -1;
    }

    public <T> T queryForOne(Class<T> type,String sql,Object ...args){
        Connection connection= JdbcUtils.getconnection();
        try {
            return queryRunner.query(connection,sql,new BeanHandler<T>(type),args);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JdbcUtils.close(connection);
        }
        return null;
    }

    public <T>List<T> queryForList(Class<T> type,String sql,Object ...args){
        Connection connection= JdbcUtils.getconnection();
        try {
            return queryRunner.query(connection,sql,new BeanListHandler<T>(type),args);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JdbcUtils.close(connection);
        }
        return null;
    }

    public Object queryForSinglValue(String sql,Object ...args){
        Connection connection=JdbcUtils.getconnection();
        try {
            return queryRunner.query(connection,sql,new ScalarHandler(),args);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JdbcUtils.close(connection);
        }
        return null;
    }
}
